//发送验证码倒计时模块
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mtf/app/theme/app_colors.dart';


class VercodeTimerWidget extends StatefulWidget {
  Color? textColor;
  final VoidCallback? onPressed;
  VercodeController controller;

  VercodeTimerWidget(this.controller,{this.onPressed,this.textColor});

  @override
  _VercodeTimerWidgetState createState() => _VercodeTimerWidgetState(controller,onPressed,textColor);
}

class VercodeController extends ChangeNotifier {
  bool sendResult=false;
  void vercodeSend(){
    sendResult=true;
    notifyListeners();
  }
}
class _VercodeTimerWidgetState extends State<VercodeTimerWidget> {
  VercodeController controller;
  final VoidCallback? onPressed;
  Color? textColor;
  _VercodeTimerWidgetState(this.controller,this.onPressed,this.textColor);

  Timer? _timer;

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      if(controller.sendResult){
        startCountdown();
      }
    });
  }
  //倒计时数值
  var _countdownTime = 0;
  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed:_countdownTime==0?btnPress():null,
      child: Text(handleCodeAutoSizeText(),
          style: TextStyle(
            color: textColor ?? Colors.white,
            fontSize: 12
          )),
    );
  }


  btnPress(){
    if(_countdownTime==0) {
      return () {
        onPressed!();
      };
    }
  }

  String handleCodeAutoSizeText() {
    if (_countdownTime > 0) {
      return '$_countdownTime'+'s';
    } else
      return '获取验证码';
  }

  call (timer) {
    if (_countdownTime < 1) {
      print("定时器取消了");
      _timer?.cancel();
      _timer=null;
    } else {
    setState(() {
    _countdownTime -= 1;
    });
    }
    print(_countdownTime);
  }

  //倒计时方法
  startCountdown() {
    print("我竟来了");
    //倒计时时间
    _countdownTime = 60;
    print({
      _countdownTime:_countdownTime,
      _timer:_timer == null
    });
    print(_timer);
    if (_timer == null) {
    print("开启定时器");
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }


  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      print("销毁啦");
      _timer?.cancel();
    }
  }
}

